package jwei.apps.json;

import java.util.ArrayList;
import java.util.List;

import jwei.apps.objects.Review;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonToReview {

    public static Review convertToReview(JSONObject r) {
        try {
            Review rev = new Review();

            String summary = r.getString("summary");
            if (summary == null || summary.equals("")) { return null; }

            rev.setSummary(summary);

            if (r.has("date")) {
                rev.setDate(r.getString("date"));
            }

            if (r.has("overallRating")) {
                rev.setRating(r.getInt("overallRating"));
            }

            if (r.has("name")) {
                rev.setName(r.getString("name"));
            }

            return rev;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static List<Review> convertToReviews(JSONArray jarray) {
        List<Review> results = new ArrayList<Review>();
        try {
            for (int i = 0; i < jarray.length(); i++) {
                JSONObject r = jarray.getJSONObject(i);
                Review rev = convertToReview(r);
                results.add(rev);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return results;
    }

}
